package com.example.export.service.controller;


import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;


@Slf4j
@Controller
public class BaseController {
    @Autowired
    public HttpServletRequest request;
    private static final String SUPER_UID = "000000000000000000000";
    private static final String WIN11 = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134";


    public void downloadExcel(HttpServletResponse response, Workbook workbook , String fileName) {
        ServletOutputStream out=null;
        try{
            String userAgent = request.getHeader("user-agent");
            if (userAgent.equals(WIN11)) {
                fileName = URLEncoder.encode(fileName,"UTF8");
            }else if (StringUtils.isNotBlank(userAgent) && (userAgent.indexOf("Firefox") >= 0 || userAgent.indexOf("Chrome") >= 0
                    || userAgent.indexOf("Safari") >= 0)) {
                fileName= new String((fileName).getBytes(), "ISO8859-1");
            } else {
                fileName= URLEncoder.encode(fileName,"UTF8"); //其他浏览器
            }
            response.reset();// 清空输出流
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);// 设定输出文件头
            response.setContentType("application/x-download");
            out= response.getOutputStream();
            workbook.write(out);
            out.flush();
        }
        catch (Exception e) {
            log.error("BaseController.downloadExcel下载excel文件异常",e);
        } finally {
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
